package com.lg.cms.controller.news;

import com.baomidou.mybatisplus.extension.api.R;
import com.lg.cms.entity.Article;
import com.lg.cms.entity.ArticleUserLike;
import com.lg.cms.entity.Comment;
import com.lg.cms.entity.User;
import com.lg.cms.service.ArticleService;
import com.lg.cms.service.ArticleUserLikeService;
import com.lg.cms.service.CommentService;
import com.lg.cms.utils.StatsUtil;
import com.lg.cms.utils.SubjectUtil;
import net.bytebuddy.asm.Advice;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * @Description: 点赞, 评论等视图控制器
 * @Author: wuyuhang
 * @create: 2020-10-18 02:08
 */
@RestController
public class StatsController {

    @Resource
    StatsUtil statsUtil;

    @Autowired
    ArticleService articleService;
    @Autowired
    CommentService commentService;

    /**
     * 文章点赞
     * @param request
     * @param articleId
     * @return
     */
    @PostMapping("/add_like")
    public R<?> like(HttpServletRequest request, Integer articleId){
        if(articleId == null){
            return R.failed("文章不存在");
        }
        try {
            User user = SubjectUtil.getUser();
            return statsUtil.addArticleLike(articleId, user.getId());
        }catch (Exception e){
            return R.failed("请先登录");
        }
    }


    /**
     * 用户评论
     * @param request
     * @param content
     * @param articleId
     * @return
     */
    @PostMapping("/add_comment")
    public R<?> comment(HttpServletRequest request, String content, Integer articleId){
        User user = null;
        try{
            user = SubjectUtil.getUser();
        }catch (Exception e){
            return R.failed("请先登录再评论");
        }
        if(user == null){
            return R.failed("请先登录再评论");
        }
        if(content == null){
            return R.failed("评论内容不能为空");
        }
        if(articleId == null){
            return R.failed("文章id为空");
        }
        Article article = articleService.getById(articleId);
        if(article == null){
            return R.failed("文章不存咋");
        }
        if(!article.getComment()){
            return R.failed("文章设置无法评论");
        }
        Comment comment = new Comment();
        comment.setCheck(false);
        comment.setArticleId(articleId);
        comment.setContent(content);

        comment.setUserId(user.getId());
        boolean result = commentService.save(comment);
        if(!result){
            return R.failed("评论失败");
        }
        //评论成功, 待管理员审核
        return R.ok(comment);
    }
}